package cn.source.system.common.Util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * <p>RandomUtils.java此类用于</p>
 * <p>@author:YXZhou</p>
 * <p>@remark:</p>
 */
public class RandomUtils {
    private static String[] randomValues = new String[]{"0","1","2","3","4","5","6","7","8","9",
        "a","b","c","d","e","f","g","h","i","j","k","m","n","u",
        "t","s","o","x","v","p","q","r","w","y","z"};

    private static String[] randomValuesAll = new String[]{"0","1","2","3","4","5","6","7","8","9",
        "a","b","c","d","e","f","g","h","i","j","k","m","n","u",
        "t","s","o","x","v","p","q","r","w","y","z", "A", "B", "C", "D", "E", "F", "G", "H", "J", "K", "L",
        "M", "N", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y",
        "Z"};
    private static String[] randomVoice = new String[]{"0","1","2","3","4","5","6","7","8","9",
        "a","b","c","d","e","f"};

    public static String getUsername(int lenght){
        StringBuffer str = new StringBuffer();
        for(int i = 0;i < lenght; i++){
            Double number=Math.random()*(randomValues.length-1);
            str.append(randomValues[number.intValue()]);
        }
        return str.toString();
    }
    public static String getVoiceRandom(int lenght){
        StringBuffer str = new StringBuffer();
        for(int i = 0;i < lenght; i++){
            Double number=Math.random()*(randomVoice.length-1);
            str.append(randomVoice[number.intValue()]);
        }
        return str.toString();
    }
    public static String getRandom(int lenght){
        StringBuffer str = new StringBuffer();
        for(int i = 0;i < lenght; i++){
            Double number=Math.random()*(randomValuesAll.length-1);
            str.append(randomValuesAll[number.intValue()]);
        }
        return str.toString();
    }
    /**
     * MD5加密，可返回32位、16位根据需要调整
     * @param sourceStr
     * @return
     */
    public static String strToMd5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte[] b = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
        } catch (NoSuchAlgorithmException e) {
        }
        return result.substring(18, 24);
    }
    public static void main(String[] args){
        System.out.println(RandomUtils.getUsername(7));
        System.out.println(strToMd5("123"));
    }
}
